<template>
  <div class="tab-wrap">
    <el-tabs
      v-model="currentTab"
      type="border-card"
      closable
      @tab-remove="removeTab"
      @tab-click="clickTab"
    >
      <el-tab-pane
        v-for="item in tabList"
        :key="item.id"
        :label="item.title"
        :name="item.id"
        class="tab-pane-wrap"
      >
      </el-tab-pane>
    </el-tabs>
    <div class="view-wrap">
      <router-view v-slot="{ Component }">
        <keep-alive>
          <component
            :is="Component"
            v-if="route.meta.keepAlive"
            :key="route.fullPath"
            class="view"
          />
        </keep-alive>
        <component
          :is="Component"
          v-if="!route.meta.keepAlive"
          :key="route.fullPath"
          class="view"
        />
      </router-view>
    </div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useTabStore } from '@/stores/tabStore'
import { storeToRefs } from 'pinia'
import { v4 as uuidv4 } from 'uuid'

const { tabList, currentTab, closeId, resize } = storeToRefs(useTabStore())
const router = useRouter()
const route = useRoute()

onMounted(() => {
  if (tabList.value.length <= 0) {
    const uuid = uuidv4()
    const initTabData = {
      id: uuid,
      name: 'local',
      type: 'local',
      title: '本地连接'
    }
    tabList.value.push(initTabData)
  }
  const data = tabList.value[0]
  currentTab.value = data.id
  router.push({ name: data.name, query: { id: data.id } })
})

const removeTab = (targetId) => {
  const tabs = tabList.value
  if (tabs.length <= 1) {
    return
  }
  closeId.value = targetId
  let activeId = currentTab.value
  if (activeId === targetId) {
    tabs.forEach((tab, index) => {
      if (tab.id === targetId) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeId = nextTab.id
        }
      }
    })
  }

  currentTab.value = activeId
  tabList.value = tabs.filter((tab) => tab.id !== targetId)
  const tabData = tabList.value.find((tab) => tab.id === currentTab.value)
  if (tabData.type === 'ssh') {
    router.push({ name: tabData.name, query: { id: tabData.id, hostId: tabData.hostId } })
  } else {
    router.push({ name: tabData.name, query: { id: tabData.id } })
  }
}

const clickTab = (tab) => {
  currentTab.value = tab.paneName
  const tabData = tabList.value.find((tab) => tab.id === currentTab.value)
  resize.value = uuidv4()
  if (tabData.type === 'ssh') {
    router.push({ name: tabData.name, query: { id: tabData.id, hostId: tabData.hostId } })
  } else {
    router.push({ name: tabData.name, query: { id: tabData.id } })
  }
}
</script>

<style lang="less" scoped>
:deep(.el-tabs--border-card > .el-tabs__content) {
  padding: 0;
}
</style>
